package com.atguigu.oss.controller;

import com.atguigu.commonutils.R;
import com.atguigu.oss.service.NonStaticResourceHttpRequestHandler;
import com.atguigu.oss.service.VideoService;
import com.atguigu.servicebase.exceptionHandler.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

//上传文件
@Api(description = "上传文件")
@RestController
@RequestMapping("/eduoss/fileoss")
//@CrossOrigin
@Slf4j
public class UploadController {
    //封面文件夹，后续用@Value从配置文件取值
    private String cover = "cover";
    private String video = "video";

    @Autowired
    private VideoService videoService;

    @Autowired
    private NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

    @ApiOperation("删除文件")
    @DeleteMapping("/delete/{type}/{originalFilename}")
    public R delete(@PathVariable String type,@PathVariable String originalFilename){
        try {
            if(type.equals(cover)){
                File file = new File(System.getProperty("user.dir")+"\\ossdata\\"+cover+"\\"+originalFilename);
                file.delete();
            }else if(type.equals(video)){
                File file = new File(System.getProperty("user.dir")+"\\ossdata\\"+video+"\\"+originalFilename);
                file.delete();
            }else if(type.equals("default")){
                File file = new File(System.getProperty("user.dir")+"\\ossdata\\"+originalFilename);
                file.delete();
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new GuliException(20001,"删除文件出错");
        }

        return R.ok();
    }

    @ApiOperation("删除多个文件")
    @DeleteMapping("/delete-bath/{type}")
    public R deleteBatch(@PathVariable String type,@RequestParam("videoIdList") List<String> videoIdList){
        if(type.equals(video)){
            videoService.removeMoreVideo(video,videoIdList);
        }
        return R.ok();
    }

    @ApiOperation("上传单个文件")
    @PostMapping("/upload")
    public R upload(@ApiParam(name = "file", value = "文件", required = true) @RequestPart("file") MultipartFile headFile) {

        if(!headFile.isEmpty()){
            //保存文件到oss服务器
            String[] name = headFile.getOriginalFilename().split("\\.");
            String prifx = "."+name[name.length-1];
            String originalFilename = UUID.randomUUID().toString()+prifx;
            try {
                headFile.transferTo(new File(System.getProperty("user.dir")+"\\ossdata\\"+originalFilename));
                log.info("上传成功");
                //返回上传到oss的路径
                String url = "/eduoss/fileoss/download/"+originalFilename;
                return R.ok().data("url",url);
            }catch (Exception e){
                e.printStackTrace();
                throw new GuliException(20001,"文件上传失败");
            }
        }

        return R.error().message("文件上传失败");
    }

    @ApiOperation("下载文件")
    @GetMapping("/download/{filename}")
    public void downLoad(@ApiParam(name = "filename", value = "文件名", required = true) @PathVariable("filename") String filename,HttpServletResponse response) throws UnsupportedEncodingException {
        String filePath = System.getProperty("user.dir")+"\\ossdata\\" ;
        File file = new File(filePath + "\\" + filename);
        if(file.exists()){
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename,"utf8"));
            byte[] buffer = new byte[1024];
            //输出流
            OutputStream os = null;
            try(FileInputStream fis= new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);) {
                os = response.getOutputStream();
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @ApiOperation("上传课程封面")
    @PostMapping("/upload/cover")
    public R cover(@ApiParam(name = "file", value = "文件", required = true) @RequestPart("file") MultipartFile headFile) {

        if(!headFile.isEmpty()){
            //保存文件到oss服务器
            String[] name = headFile.getOriginalFilename().split("\\.");
            String prifx = "."+name[name.length-1];
            String originalFilename = UUID.randomUUID().toString()+prifx;
            try {
                headFile.transferTo(new File(System.getProperty("user.dir")+"\\ossdata\\"+cover+"\\"+originalFilename));
                log.info("上传成功");
                //返回上传到oss的路径
                String url = "/eduoss/fileoss/download/"+cover+"/"+originalFilename;
                return R.ok().data("url",url);
            }catch (Exception e){
                e.printStackTrace();
                throw new GuliException(20001,"文件上传失败");
            }
        }

        return R.error().message("文件上传失败");
    }

    @ApiOperation("下载文件")
    @GetMapping("/download/cover/{filename}")
    public void downloadCover(@ApiParam(name = "filename", value = "文件名", required = true) @PathVariable("filename") String filename,HttpServletResponse response) throws UnsupportedEncodingException {
        String filePath = System.getProperty("user.dir")+"\\ossdata\\"+cover+"\\" ;
        File file = new File(filePath + "\\" + filename);
        if(file.exists()){
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename,"utf8"));
            byte[] buffer = new byte[1024];
            //输出流
            OutputStream os = null;
            try(FileInputStream fis= new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);) {
                os = response.getOutputStream();
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @ApiOperation("视频播放")
    @GetMapping("/download/video/{filename}")
    public void downloadVideo(@PathVariable String filename) throws Exception{
        HttpServletRequest request =((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

        String realPath = System.getProperty("user.dir")+"\\ossdata\\"+video+"\\"+filename;
        //假如我把视频1.mp4放在了static下的video文件夹里面
        //sourcePath 是获取resources文件夹的绝对地址
        //realPath 即是视频所在的磁盘地址
//        String sourcePath = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1);
//        String realPath = sourcePath +"static/video/1.mp4";

        Path filePath = Paths.get(realPath );
        if (Files.exists(filePath)) {
            String mimeType = Files.probeContentType(filePath);
            if (!StringUtils.isEmpty(mimeType)) {
                response.setContentType(mimeType);
            }
            request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, filePath);
            nonStaticResourceHttpRequestHandler.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }

    @ApiOperation("上传单个文件")
    @PostMapping("/upload/video")
    public R uploadVideo(@RequestPart("file") MultipartFile headFile) {

        if(!headFile.isEmpty()){
            //保存文件到oss服务器
            String[] name = headFile.getOriginalFilename().split("\\.");
            String prifx = "."+name[name.length-1];
            String originalFilename = UUID.randomUUID().toString()+prifx;
            try {
                headFile.transferTo(new File(System.getProperty("user.dir")+"\\ossdata\\"+video+"\\"+originalFilename));
                log.info("上传成功");
                //返回上传到oss的路径
                String url = "/eduoss/fileoss/download/"+video+"/"+originalFilename;
                return R.ok().data("videoId",url);
            }catch (Exception e){
                e.printStackTrace();
                throw new GuliException(20001,"文件上传失败");
            }
        }

        return R.error().message("文件上传失败");
    }
}
